package com.atguigu.flink.chapter02_DataStreamAPI.process;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/10/22
 *
 *      求所有传感器的水位和.
 *
 *              全局累加，必须保证所有的数据，输入到同一个并行度！
 */
public class Demo13_ProcessAll
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .process(new ProcessFunction<WaterSensor, Integer>()
           {
               //作为某个并行度的属性，每个Task都有自己的sum
               int sum = 0;
               /*
                    输入的每一个数据，都会调用一次
                        WaterSensor value： 输入的数据
                        Context ctx：   应用的上下文，从这个对象中获取运行环境中的很多信息。
                                            例如： watermark，处理时间等等
                        Collector<Integer> out： 将结果收集输出
                */
               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<Integer> out) throws Exception {

                   sum += value.getVc();

                   out.collect(sum);

               }
           }).setParallelism(1)
           .print();


        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
